package com.yugu.park.task;

import com.yugu.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;

/**
 * @author Noble-Six
 */
@Component
@Slf4j
public class BackupTask {
	@Value("${db.dbName}")
    private String dbName;
	@Value("${db.host}")
	private String host;
	@Value("${db.username}")
	private String username;
	@Value("${db.password}")
	private String password;
	@Value("${file.path}")
	private String savePath;
	/**
	 * 数据备份开始
	 */
	@Async("dbBackupServiceExecutor")
	public void doBackup() {
		String fileName = DateUtil.getTodayShort();
		File saveFile = new File(savePath);
        // 如果目录不存在
        if (!saveFile.exists()) {
            // 创建文件夹
            saveFile.mkdirs();
        }
        if (!savePath.endsWith(File.separator)) {
            savePath = savePath + File.separator;
        }
 
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("mysqldump").append(" --opt").append(" -h").append(host);
        stringBuilder.append(" --user=").append(username) .append(" --password=").append(password).append(" --lock-all-tables=true");
        stringBuilder.append(" --result-file=").append(savePath + fileName+".sql ").append(dbName);
        System.out.println(stringBuilder.toString());
        try {
            Process process = Runtime.getRuntime().exec(stringBuilder.toString());
            log.info("数据库备份状态：{} 已被停用.", process.waitFor());
            process.destroy();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
        	log.error("数据库备份等待中------------------------------");
            e.printStackTrace();
        }
	}
}
